import React, { useEffect, useState } from "react";
import { Input, Button, Space, Table, Image, Form, Radio, DatePicker, Modal, notification, Upload, message } from 'antd';
import { useHistory } from 'dva';
import { getAllSinger, setSinger, delSinger, updateSinger, updateSingerPic } from '../../api';
import "./singer.css";
import { newDatetype } from "../../utils/newDate";
import 'moment/locale/zh-cn';
import moment from 'moment';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { UserOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getPageInfo } from "./singer.config";


export default function Singer() {
    const { Search } = Input;
    const [formUpdate] = Form.useForm();
    const [formamend] = Form.useForm();
    // const [formpic] = Form.useForm();
    const { confirm } = Modal;
    const [filterParams, setFilterParams] = useState(getPageInfo());
    const [total, setTotal] = useState(0);
    const history = useHistory()
    const [tableDatas, setTableDatas] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [open, setOpen] = useState(false);
    // const [nopen, setnOpen] = useState(false);
    const [deletes, setDeletes] = useState([])
    const dateFormat = "YYYY/MM/DD";
    const [value, setValue] = useState(1);
    const onChange = (e) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };
    const props = {
        name: 'file',
        action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };
    useEffect(() => {
        getAllSingers();
    }, []);
    console.log(getAllSinger())
    const getAllSingers = async () => {
        const data = await getAllSinger();

        console.log(data)
        // console.log(data)
        data.forEach(item => {
            item.key = item.id
        })
        setTableDatas(data)
    }

    const singerId = async (val) => {
        // console.log(val)
        history.push(`/detail?singerId=${val}`)
    }

    const columns = [
        {
            title: '歌手图片',
            dataIndex: 'pic',
            key: "id",
            render: (text, item) => {
                return (
                    <div>
                        <Image width={50} src={item.pic} />
                        {/* <Space size="middle">
                            <Button 
                            // onClick={() => setsingerpic(item)}
                            >更新图片</Button>
                        </Space> */}
                    </div>
                )
            },
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: "id",
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: "id",
            render: (text, item) => {
                item = item.sex
                return item == 0 ? "女" : item == 1 ? "男" : item == 2 ? "组合" : "不明";
            }
        },
        {
            title: '出生日期',
            dataIndex: 'birth',
            key: "id",
        },
        {
            title: '地区',
            dataIndex: 'location',
            key: "id",
        },
        {
            title: '简介',
            dataIndex: 'introduction',
            key: "id",
            render: (text, item) => (
                <div className="singerjs">{item.introduction}</div>
            ),
        },
        {
            title: '歌曲管理',
            dataIndex: 'action',
            key: "id",
            render: (item, text,) => (
                <Space size="middle">
                    <a href="http://localhost:3000/#/SongInformation">
                        <Button
                        // onClick={() => singerId(text.id)}
                        >歌曲管理</Button>
                    </a>
                </Space>
            ),
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'id',
            render: (_, record) => (
                <Space size="middle">
                    <Button onClick={() => getDataDetail(record)} >编辑</Button>
                    <Button onClick={() => dellist('success', record.id)} danger>删除</Button>
                </Space>
            ),
        },
    ];

    const paginationChange = (page, pageSize) => {
        setFilterParams({ ...filterParams, page });
    };

    // const filterChange = (value) => {
    //     setFilterParams({ ...filterParams, ...value });
    // };

    const handleOk = async () => {
        const data = formUpdate.getFieldsValue(true);
        console.log(data);
        console.log(data.birth)
        data.birth = newDatetype(data.birth._d)
        let setSingers = new URLSearchParams();
        setSingers.append('name', data.name);
        setSingers.append('sex', data.sex);
        setSingers.append('pic', "/img/singerPic/hhh.jpg");
        setSingers.append('birth', data.birth);
        setSingers.append('location', data.location);
        setSingers.append('introduction', data.introduction);
        await setSinger(setSingers)
        formUpdate.resetFields();
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        console.log(getAllSinger.id)
        formUpdate.resetFields();
        setIsModalOpen(false);
    };


    const getDataDetail = (val) => {
        formamend.setFieldsValue(val)
        setOpen(true);
    }
    const Ok = async () => {
        const arr = formamend.getFieldsValue(true)
        console.log(arr.birth)

        arr.birth = moment(arr.birth)
        console.log(arr.birth)

        let setSingers = new URLSearchParams();
        setSingers.append('id', arr.id);
        setSingers.append('name', arr.name);
        setSingers.append('sex', arr.sex);
        setSingers.append('birth', arr.birth);
        setSingers.append('location', arr.location);
        setSingers.append('introduction', arr.introduction);
        await updateSinger(setSingers);
        getAllSingers();
        setOpen(false);
        formamend.resetFields()
    };
    const Cancel = () => {
        setOpen(false);
        formamend.resetFields()
    };

    const onSearch = async (value) => {
        var s = JSON.stringify(tableDatas)
        // console.log(s)
        var d = JSON.parse(s)
        // console.log(d)
        var html = [];
        let arrnew = d.map((item, index) => {
            return Object.assign(
                {},
                {
                    name: item.name,
                    birth: item.birth,
                    sex: item.sex,
                    id: item.id,
                    pic: item.pic,
                    location: item.location,
                    introduction: item.introduction,
                }
            );
        });

        var newData = arrnew.filter((item) => {
            if (item.name.indexOf(value) > -1) {
                return item;
            }
            return newData;
        });
        // console.log(newData)

        if (newData.length > 0) {
            for (var i = 0; i < newData.length; i++) {
                html.push(newData[i])
            }
        }
        // console.log(html)
        setTableDatas(html)

    };

    const tableSelectionChange = (val) => {
        setDeletes(val)
    }
    // console.log(tableSelectionChange)
    const dellist = (type, val) => {
        confirm({
            title: '确认永久删除吗',
            icon: <ExclamationCircleOutlined />,
            content: '删除后不可恢复',
            async onOk() {
                val === undefined ? await delSinger(deletes) : await delSinger(val)
                notification[type]({
                    message: '删除成功',
                    duration: 1,
                });
                getAllSingers()
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    return (
        <div id="singer">
            <div className="singerdiv"><UserOutlined />歌手管理</div>
            <div className="singer-box">
                <Space>
                    姓名：
                    <Search style={{ width: 400 }} placeholder="请输入歌手姓名" onSearch={onSearch} enterButton />
                    <Button type="primary" onClick={() => setIsModalOpen(true)}>添加</Button>
                </Space>
            </div>
            <Table style={{ marginTop: "20px" }}
                scroll={{ x: 'calc(1400px + 20% )', y: 400 }}
                columns={columns} dataSource={tableDatas} pagination={{ total, current: filterParams.page, pageSize: filterParams.size, onChange: paginationChange }} />

            <Modal title="添加歌手" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText="确认" cancelText="取消">
                <Form form={formUpdate}>
                    <Form.Item label="歌手名" name="name">
                        <Input />
                    </Form.Item>
                    <Form.Item label="性&nbsp;&nbsp;&nbsp;&nbsp;别" name="sex">
                        <Radio.Group onChange={onChange} value={value}>
                            <Space size="large">
                                <div></div>
                                <Radio value={0}>女</Radio>
                                <Radio value={1}>男</Radio>
                                <Radio value={2}>组合</Radio>
                                <Radio value={3}>不明</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="生&nbsp;&nbsp;&nbsp;&nbsp;日" name="birth">
                        <DatePicker />
                    </Form.Item>
                    <Form.Item label="地&nbsp;&nbsp;&nbsp;&nbsp;区" name="location">
                        <Input />
                    </Form.Item>
                    <Form.Item label="简&nbsp;&nbsp;&nbsp;&nbsp;介" name="introduction">
                        <Input.TextArea />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal title="修改歌手" open={open} onOk={Ok} onCancel={Cancel} okText="确认" cancelText="取消">
                <Form form={formamend}>
                    <Form.Item label="歌手名" name="name">
                        <Input />
                    </Form.Item>
                    <Form.Item label="性&nbsp;&nbsp;&nbsp;&nbsp;别" name="sex">
                        <Radio.Group onChange={onChange} value={value}>
                            <Space size="large">
                                <div></div>
                                <Radio value={0}>女</Radio>
                                <Radio value={1}>男</Radio>
                                <Radio value={2}>组合</Radio>
                                <Radio value={3}>不明</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="生&nbsp;&nbsp;&nbsp;&nbsp;日" name="birth">
                        <DatePicker locale={locale} />;
                    </Form.Item>
                    <Form.Item label="地&nbsp;&nbsp;&nbsp;&nbsp;区" name="location">
                        <Input />
                    </Form.Item>
                    <Form.Item label="简&nbsp;&nbsp;&nbsp;&nbsp;介" name="introduction">
                        <Input.TextArea />
                    </Form.Item>
                </Form>
            </Modal>

            {/* <Modal title="修改图片" open={nopen} onOk={nOk} onCancel={nCancel} okText="确认" cancelText="取消">
                <Form form={formpic}>
                    <Form.Item name="pic">
                        <Upload {...props}>
                            <Button>上传图片</Button>
                        </Upload>
                    </Form.Item>
                </Form>
            </Modal> */}
        </div >
    )
}